import cantools
import json
import os

# 在 json 中加入 dbc 信息
class Dbc_obj:
    def __init__(self,json_path):
        self._json_path = json_path
        print("Interction module: dbc object create one")
    def AddInfo_matchJSON(self):
        # 打开 JSON 文件并加载数据
        with open(self._json_path, 'r') as f:
            data = json.load(f)
            
        # 修改 JSON 数据
        data['name'] = 'ChatGPT'
        data['age'] = 1
        
        data = json_update_data(data)
        
        with open(self._json_path, 'w') as f:
            json.dump(data, f)
        
# 加载DBC文件
db = cantools.database.load_file('./project/configure/Interaction/C03-001-020MM01 CAN DateBase for SC_CANFD_V4.0.dbc')
db1 = cantools.database.load_file('./project/configure/Interaction/C01D-006-014DB01  CAN DataBase for SC-CANFD_V4.2.dbc')
db2 = cantools.database.load_file('./project/configure/Interaction/ES11-A-001-020MM01 C_Matrix for SC_CANFD_V2.8确认版.dbc')

# 获取信号所在的报文信息
def get_message_by_signal_name(signal_name):
    # 遍历第一个dbc，寻找信号
    for message in db.messages:
        for signal in message.signals:
            if signal.name.lower() == signal_name.lower():
                return message
    # 找不到 信号，遍历第二个 dbc
    for message in db1.messages:
        for signal in message.signals:
            if signal.name.lower() == signal_name.lower():
                return message
    # 找不到信号，遍历第三个 dbc
    for message in db2.messages:
        for signal in message.signals:
            if signal.name.lower() == signal_name.lower():
                return message
            
# 获取信号所在的消息名称和消息ID
def get_message_info_by_signal_name(signal_name):
    message = get_message_by_signal_name(signal_name)
    if message is not None:
        message_info = {'name': message.name, 'id': message.frame_id}
        return message_info
    else:
        print("Interction module:",signal_name, "search resrult in dbc: none !!!")
        return None
    
# 遍历整个 json 进行更新，补充信号的对应的 message name ， message id
def json_update_data(data):
    if isinstance(data, list):
        for i in range(len(data)):
            data[i] = json_update_data(data[i])
    elif isinstance(data, dict):
        for key, value in data.items():
            if key == "signal_name":
                signal_name = data[key]
                message_info = get_message_info_by_signal_name(signal_name)
                if message_info is not None:
                    data['message_name'] = message_info['name']
                    data['message_id'] = message_info['id']
                    data['message_id_hex'] = hex(message_info['id'])
            data[key] = json_update_data(value)
    else:
        # 这里可以对其他类型的数据进行修改
        pass

    return data
